package db;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
 * @author: wzq
 * @date: 14-6-17
 * description: change it at File | setting | File and code templates | include | file header
 */
public class RandomGenerator {
    private static final String AB = "0123456789" +
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
            "abcdefghijklmnopqrstuvwxyz" +
            "_";
    static Random rnd = new Random();

    public static String randomString(int len) {
        StringBuilder sb = new StringBuilder(len);
        for(int i = 0; i < len; i++)
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        return sb.toString();
    }

    /**
     * [ceil,floor)
     */
    public static int randomInt(int ceil, int floor) {
        float f = rnd.nextFloat();
        return (int) (ceil + f * (ceil - floor));
    }

    public static byte[] randomBytes(int length) {
        byte[] b = new byte[length];
        rnd.nextBytes(b);
        return b;
    }

    public static float randomFloat(int ceil, int floor) {
        return ceil + rnd.nextFloat() * (ceil - floor);
    }

    public static boolean randomBool() {
        return rnd.nextFloat() > 0.5f;
    }

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    public static final String def_start = "1970-01-01";
    /**
     * 随机日期生成器
     *
     * @param start 日期格式 yyyy-MM-dd 起始时间 null 表示1970-01-01
     * @param end 日期格式 yyyy-MM-dd 结束事件 null 表示现在的日期
     *
     * @return 日期格式 yyyy-MM-dd 的事件
     */
    public static Date randomDate(String start, String end) {
        Date from = null;

        // prepare llegal from data

        try {
            from = sdf.parse(start);
        } catch(ParseException e) {
            e.printStackTrace();
        } catch(NullPointerException e) {
            //e.printStackTrace();
        }

        if(from == null) {
            try {
                from = sdf.parse(def_start);
            } catch(Exception e) {// never happen
                e.printStackTrace();
            }
        }

        // prepare llegal to data
        Date to = null;
        try {
            to = sdf.parse(end);
        } catch(ParseException e) {
            e.printStackTrace();
        } catch(NullPointerException e) {
            //e.printStackTrace();
        }

        if(to == null) {
            to = new Date();
        }

        long period = to.getTime() - from.getTime();
        long spot = from.getTime() + (long) (period * rnd.nextFloat());

        Date d = new Date(spot);
        return d;
    }

    public static void main(String[] args) {
        Date date = randomDate("1999-01-01", "1999-12-31");
        System.out.println(sdf.format(date));
    }
}
